package com.ruoyi.dr.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.dr.domain.DrOwnerUnion;
import com.ruoyi.dr.domain.DrSampledata;
import com.ruoyi.dr.domain.DrSellAnalysis;
import com.ruoyi.dr.mapper.DrOwnerUnionMapper;
import com.ruoyi.dr.mapper.DrSampledataMapper;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.poi.util.ArrayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.dr.mapper.DrSellDetailsMapper;
import com.ruoyi.dr.domain.DrSellDetails;
import com.ruoyi.dr.service.IDrSellDetailsService;

import javax.annotation.Resource;

/**
 * 销售明细Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-14
 */
@Service
public class DrSellDetailsServiceImpl implements IDrSellDetailsService 
{
    private static final Logger log = LoggerFactory.getLogger(DrSellDetailsServiceImpl.class);

    @Autowired
    private DrSellDetailsMapper drSellDetailsMapper;
    @Resource
    private DrSampledataMapper drSampledataMapper;
    @Resource
    private DrOwnerUnionMapper drOwnerUnionMapper;


    /**
     * 查询销售明细
     * 
     * @param orderId 销售明细主键
     * @return 销售明细
     */
    @Override
    public DrSellDetails selectDrSellDetailsByOrderId(String orderId)
    {
        return drSellDetailsMapper.selectDrSellDetailsByOrderId(orderId);
    }

    /**
     * 查询销售明细列表
     * 
     * @param drSellDetails 销售明细
     * @return 销售明细
     */
    @Override
    public List<DrSellDetails> selectDrSellDetailsList(DrSellDetails drSellDetails)
    {
        return drSellDetailsMapper.selectDrSellDetailsList(drSellDetails);
    }

    /**
     * 查询销售明细列表
     *
     * @param sellAnalysis 销售明细
     * @return 销售明细
     */
    @Override
    public List<DrSellAnalysis> selectDrSellAnalysisList(DrSellAnalysis sellAnalysis) {
        if (StringUtils.isNotNull(sellAnalysis.getOwner())) {
            DrOwnerUnion drOwnerUnion = new DrOwnerUnion();
            drOwnerUnion.setOwner(sellAnalysis.getOwner());
            List<DrOwnerUnion> drOwnerUnions = drOwnerUnionMapper.selectByOwner(drOwnerUnion);
            Object[] awemeIdArray = drOwnerUnions.stream()
                    .map(DrOwnerUnion::getAwemeId).toArray();
            sellAnalysis.setAwemeIdArray(awemeIdArray);
        }

        return drSellDetailsMapper.selectDrSellAnalysis(sellAnalysis);
    }

    /**
     * 新增销售明细
     * 
     * @param drSellDetails 销售明细
     * @return 结果
     */
    @Override
    public int insertDrSellDetails(DrSellDetails drSellDetails)
    {
        return drSellDetailsMapper.insertDrSellDetails(drSellDetails);
    }

    /**
     * 修改销售明细
     * 
     * @param drSellDetails 销售明细
     * @return 结果
     */
    @Override
    public int updateDrSellDetails(DrSellDetails drSellDetails)
    {
        return drSellDetailsMapper.updateDrSellDetails(drSellDetails);
    }

    /**
     * 批量删除销售明细
     * 
     * @param orderIds 需要删除的销售明细主键
     * @return 结果
     */
    @Override
    public int deleteDrSellDetailsByOrderIds(String[] orderIds)
    {
        return drSellDetailsMapper.deleteDrSellDetailsByOrderIds(orderIds);
    }

    /**
     * 删除销售明细信息
     * 
     * @param orderId 销售明细主键
     * @return 结果
     */
    @Override
    public int deleteDrSellDetailsByOrderId(String orderId)
    {
        return drSellDetailsMapper.deleteDrSellDetailsByOrderId(orderId);
    }

    /**
     * 查询补样信息
     *
     * @param sellAnalysis 销售明细
     * @return 结果
     */
    @Override
    public List<DrSellAnalysis> selectCountByAwemeProductOwner(DrSellAnalysis sellAnalysis) {
        DrSampledata drSampledata = new DrSampledata();
        List<DrSellAnalysis> drSellAnalyses = drSellDetailsMapper.selectCountByAwemeProductOwner(sellAnalysis);
        if (StringUtils.isNotNull(sellAnalysis.getOwner())) {
            DrOwnerUnion drOwnerUnion = new DrOwnerUnion();
            drOwnerUnion.setOwner(sellAnalysis.getOwner());
            //查找归属信息
            List<DrOwnerUnion> ownerUnion = drOwnerUnionMapper.selectByOwner(drOwnerUnion);
            List<String> awemeIdList = ownerUnion.stream().map(DrOwnerUnion::getAwemeId).collect(Collectors.toList());

            drSampledata.setAwemeIdArray(awemeIdList.toArray(new String[awemeIdList.size()]));

        }
        // 查询寄样表信息
        List<DrSampledata> drSampledataList = drSampledataMapper.selectDrSampledataAnalysis(drSampledata);
        Map<String, List<DrSampledata>> awemeIdMap = new HashMap<>();
        for (DrSampledata sampledata : drSampledataList) {
            if (Objects.isNull(awemeIdMap.get(sampledata.getAwemeId()))) {

                List<DrSampledata> list = drSampledataList.stream()
                                .filter(e -> StringUtils.equals(e.getAwemeId(), sampledata.getAwemeId()))
                                .collect(Collectors.toList());
                awemeIdMap.put(sampledata.getAwemeId(), list);
            }
        }

//        drSampledataList.stream()
        // 达到补样标准的人员信息
        drSellAnalyses = drSellAnalyses.stream()
                .filter(e -> Integer.parseInt(e.getTotalCount()) > 10)
                .sorted(Comparator.comparing(DrSellAnalysis::getProductId).reversed())
                .collect(Collectors.toList());
        List<DrSellAnalysis> list = new ArrayList<>();
        for (DrSellAnalysis drSellAnalysis : drSellAnalyses) {
            // 如果总销量大于10再显示
            if (Integer.parseInt(drSellAnalysis.getTotalCount()) > 10) {
                List<DrSampledata> sampledataList = awemeIdMap.get(drSellAnalysis.getAwemeId());
                if (Objects.nonNull(sampledataList)) {
                    DrSampledata singleDrSampledata = null;
                    for (DrSampledata sampledata : sampledataList) {

                        if (StringUtils.equals(drSellAnalysis.getProductId(), sampledata.getProductId())) {
                            singleDrSampledata = sampledata;
                        }
                    }
                    if (Objects.nonNull(singleDrSampledata)) {
                        drSellAnalysis.setDayDateStart(singleDrSampledata.getTime());
                        drSellAnalysis.setSampleCount(singleDrSampledata.getNum().toString());
                        list.add(drSellAnalysis);
                    } else {
                        drSellAnalysis.setDayDateStart(null);
                        drSellAnalysis.setSampleCount("0");
                        list.add(drSellAnalysis);
                    }

                }

            }
        }
        return list;
    }


    /**
     * 导入销售数据
     *
     * @param sellDetails 销售详细数据列表
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importSellDetails(List<DrSellDetails> sellDetails, String operName) {
        if (StringUtils.isNull(sellDetails) || sellDetails.size() == 0) {
            throw new ServiceException("导入销售详细数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        // k:达人号  v:商品id 避免更新老是更新寄样表，同一批只导入一次某个达人的某个商品id
        Map<String, List<String>> map = new HashMap<>();
        for (DrSellDetails sellDetail : sellDetails) {
            try {
                // 验证是否存在这个订单信息
                DrSellDetails s = drSellDetailsMapper.selectDrSellDetailsByOrderId(sellDetail.getOrderId());

                if (StringUtils.isNull(s)) {
//                    map
                    /**   以下都为寄样表更新的对应代码   */
                    map = setSampleData(map, sellDetail);

                    // 插入数据
                    drSellDetailsMapper.insertDrSellDetails(sellDetail);
                    successNum++;
                    successMsg.append("<br/>" + successNum + " 条数据 导入成功");
                } else {
                    // 是否完成看插入的订单信息，已完成的可以不理
                    drSellDetailsMapper.updateDrSellDetails(sellDetail);
                    successNum++;
                    successMsg.append("<br/>" + successNum + " 条数据 更新成功");
                }
            }
            catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "条数据： " + sellDetail.getOrderId() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }



    private Map<String, List<String>> setSampleData(Map<String, List<String>> map,
                                                    DrSellDetails sellDetail) {
            List<String> productList = map.get(sellDetail.getAwemeId());
            if (!Objects.isNull(productList)) {
                // 如果已经在这个表格里面了，那么寄样表信息不用再更新了
                for (String productData : productList) {
                    if (StringUtils.equals(productData, sellDetail.getProductId())) {
                        return map;
                    }
                }
            }

            // 如果寄样表有数据，将该达人的该商品标识为已完
            DrSampledata drSampledata = new DrSampledata();
            List<String> awemelist = new ArrayList<>();
            // 通过父项找子项
            DrOwnerUnion drOwnerUnion = drOwnerUnionMapper.selectDrOwnerUnionByAwemeId(sellDetail.getAwemeId());
            if (Objects.nonNull(drOwnerUnion)) {
                awemelist.add(drOwnerUnion.getAwemeId());
                List<DrOwnerUnion> dwOwnerUnionList = drOwnerUnionMapper.selectDrOwnerUnionByParentId(drOwnerUnion.getId());
                for (DrOwnerUnion ownerUnion : dwOwnerUnionList) {
                    awemelist.add(ownerUnion.getAwemeId());
                }
            }
            Object[] awemeIdArray = awemelist.toArray();

    //                    drSampledata.setAwemeId(sellDetail.getAwemeId());
            drSampledata.setProductId(sellDetail.getProductId());
            drSampledata.setAwemeIdArray(awemeIdArray);
            List<DrSampledata> drSampledataList = drSampledataMapper.selectDrSampledataList(drSampledata);
            if (!drSampledataList.isEmpty() && drSampledataList.size() > 1) {
                drSampledataList = drSampledataList.stream()
                        .sorted(Comparator.comparing(DrSampledata::getTime))
                        .collect(Collectors.toList());
                DrSampledata dsd = drSampledataList.get(0);
                dsd.setDone("完成");
                drSampledataMapper.updateDrSampledata(dsd);
            }
        return map;
    }




}
